﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Enemy : MonoBehaviour {

	//属性值
	public float moveSpeed = 3;
	private Vector3 bulletEulerAngles;
	private float v;
	private float h;
	//private float defendTimeVal = 5;
	//private bool isDefended = true;


	private SpriteRenderer sr;
	/*
	 * 坦克资源数组
	 * 上右下左
	 * */
	public Sprite[] tankSprite;
	public GameObject bulletPrefab;
	public GameObject explosionPrefab;
	public GameObject defendEffectPrefab;


	//计时器
	private float timeVal;
	private float timeValChangeDirection = 4;

	private void Awake()
	{
		sr = GetComponent<SpriteRenderer>();
	}

	// Use this for initialization
	void Start()
	{

	}

	// Update is called once per frame
	void Update()
	{
		if (PlayerManager.Instance.isDefeat)
		{
			return;
		}
		//攻击的时间间隔
		if (timeVal > 3)
		{
			Attack();
		}
		else
		{
			timeVal += Time.deltaTime;
		}
	}

	private void FixedUpdate()
	{
		if (PlayerManager.Instance.isDefeat)
		{
			return;
		}
		Move();
	}

	private void Attack()
	{
		//子弹产生的角度=坦克当前角度+子弹应该旋转角度
		Instantiate(bulletPrefab, transform.position, Quaternion.Euler(transform.eulerAngles + bulletEulerAngles));
		timeVal = 0;
	}

	//坦克移动方法
	private void Move()
	{
		if (timeValChangeDirection >= 4)
		{
			int num = Random.Range(0, 8);
			if (num > 5)
			{
				v = -1;
				h = 0;
			}
			else if (num == 0)
			{
				v = 1;
				h = 0;
			}
			else if (num >= 0 && num <= 2)
			{
				v = 0;
				h = -1;
			}
			else if (num > 2 && num <= 4)
			{
				v = 0;
				h = 1;
			}
			timeValChangeDirection = 0;
		}
		else
		{
			timeValChangeDirection += Time.fixedDeltaTime;
		}

		//垂直方向移动
		//v = Input.GetAxisRaw("Vertical");
		transform.Translate(Vector3.up * v * moveSpeed * Time.deltaTime, Space.World);
		if (v < 0)
		{
			sr.sprite = tankSprite[2];
			bulletEulerAngles = new Vector3(0, 0, -180);
		}
		else if (v > 0)
		{
			sr.sprite = tankSprite[0];
			bulletEulerAngles = new Vector3(0, 0, 0);
		}
		if (v != 0)
		{
			return;
		}
		/*
		 * Input.GetAxisRaw("Horizontal");这是Unity自带的函数,直接引用
		 */
		//水平方向移动
		//h = Input.GetAxisRaw("Horizontal");
		transform.Translate(Vector3.right * h * moveSpeed * Time.deltaTime, Space.World);
		if (h < 0)
		{
			sr.sprite = tankSprite[3];
			bulletEulerAngles = new Vector3(0, 0, 90);
		}
		else if (h > 0)
		{
			sr.sprite = tankSprite[1];
			bulletEulerAngles = new Vector3(0, 0, -90);
		}
	}

	//坦克销毁方法
	private void Die()
	{
		/*if (isDefended)
		{
			return;
		}*/
		Instantiate(explosionPrefab, transform.position, transform.rotation);
		Destroy(gameObject);
	}

	private void OnCollisionEnter2D(Collision2D collision2D) {
		if (collision2D.gameObject.tag == "Enemy") {
			timeValChangeDirection = 4;
		}
	}
}
